package com.lw.acl.realm;

import com.lw.acl.entity.Role;
import com.lw.acl.entity.User;
import com.lw.acl.service.UserService;
import com.lw.commonutil.result.ResultCodeEnum;
import com.lw.commonutil.utils.MD5;
import com.lw.servicebase.exception.GuliException;
import com.lw.servicebase.profile.ProfileResult;
import com.lw.servicebase.shiro.GuliRealm;
import org.apache.shiro.authc.*;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class GuliAuthRealm extends GuliRealm {

    @Autowired
    private UserService userService;
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken)authenticationToken;
        //获取用户名密码
        String username = token.getUsername();
        String password = new String( token.getPassword() );
        //查找用户
        User user = userService.selectByUsername( username );
        if (user==null){
            throw new GuliException( ResultCodeEnum.LOGIN_FAIL );
        }
        //加密比较密码
        String encrypt = MD5.encrypt( password );
        if (!encrypt.equals( user.getPassword() )){
            throw new GuliException( ResultCodeEnum.LOGIN_FAIL );
        }
        //设置安全数据
        ProfileResult result = new ProfileResult();
        result.setNickName( user.getNickName() );
        result.setSalt( user.getSalt() );
        Set<String> roles = new HashSet<>();
        List<Role> roleList = user.getRoles();
        for (int i = 0 ;i<roleList.size();i++){
            roles.add( roleList.get( i ).getRoleCode() );
        }
        result.setRoles( roles );
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(result, encrypt, this.getName() );
        return info;
    }
}
